import axios from 'axios'
import { useAuthStore } from '@/stores/auth'

const instance = axios.create({
  baseURL: 'http://localhost:5000/api',
  timeout: 10000
})

// 请求拦截器
instance.interceptors.request.use(config => {
  const authStore = useAuthStore()
  if (authStore.token) {
    config.headers.Authorization = `Bearer ${authStore.token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use(response => {
  return response.data
}, error => {
  if (error.response) {
    switch (error.response.status) {
      case 401:
        // 处理未授权
        useAuthStore().logout()
        break
      case 403:
        // 处理禁止访问
        break
      case 500:
        // 处理服务器错误
        break
    }
  }
  return Promise.reject(error)
})

export default instance